import { defineStore } from "pinia";
import axios from "axios";

export const useMainStore = defineStore("main", {
  state: () => {
    return { _user: null, _token: null };
  },
  // 所有数据持久化
  // persist: true,
  // 持久化存储插件其他配置
  persist: {
    // 修改存储中使用的键名称，默认为当前 Store的 id
    key: "arrowkey",
    // 修改为 sessionStorage，默认为 localStorage
    storage: window.sessionStorage,
  },
  getters: {
    user(state) {
      return state._user;
    },
  },
  actions: {
    login(obj) {
      return new Promise((resolve, reject) => {
        axios
          .post("/account/login", obj)
          .then((res) => {
            const { success, data, msg } = res;
            if (success) {
              this._user = data.user;
              this._token = data.token;
              resolve();
            } else {
              reject(msg);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    loginOut() {
      this._user = null;
      this._token = null;
    },
  },
});
